package com.ling.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.*;
import com.ling.service.*;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//博客管理（其它用户的博客）
@Controller
public class BlogController {

    private final UserService userService;
    private final UserAreaService userAreaService;
    private final AreaService areaService;
    private final BlogService blogService;
    private final BlogTypeService blogTypeService;
    private final BlogCommentService blogCommentService;

    private final UserUpvoteBlogService userUpvoteBlogService;
    private final UserDownvoteBlogService userDownvoteBlogService;
    private final StarBlogService starBlogService;
    private final ReportService reportService;
    private final UserFollowService userFollowService;

    private final UserMessageService userMessageService;
    private final UserTrackService userTrackService;

    @Autowired
    public BlogController(UserService userService, BlogService blogService, BlogTypeService blogTypeService, BlogCommentService blogCommentService, UserUpvoteBlogService userUpvoteBlogService, UserDownvoteBlogService userDownvoteBlogService, StarBlogService starBlogService, ReportService reportService, UserFollowService userFollowService, UserAreaService userAreaService, AreaService areaService, UserMessageService userMessageService, UserTrackService userTrackService) {
        this.userService = userService;
        this.blogService = blogService;
        this.blogTypeService = blogTypeService;
        this.blogCommentService = blogCommentService;
        this.userUpvoteBlogService = userUpvoteBlogService;
        this.userDownvoteBlogService = userDownvoteBlogService;
        this.starBlogService = starBlogService;
        this.reportService = reportService;
        this.userFollowService = userFollowService;
        this.userAreaService = userAreaService;
        this.areaService = areaService;
        this.userMessageService = userMessageService;
        this.userTrackService = userTrackService;
    }

    @RequestMapping(value = "/blog-home", method = RequestMethod.GET)
    public String goToBlogHome(ModelMap modelMap, HttpSession session) {
        //0.判断用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //用户未登录
            return "redirect:/login";
        }
        //1.用户关注领域
        List<UserArea> userAreas = userAreaService.getUserAreasByUserId(user.getId());
        if (userAreas.isEmpty()) {
            //用户未关注任何领域
            modelMap.addAttribute("areas", areaService.getArea());
            return "area-pick";
        }
        modelMap.addAttribute("userAreas", userAreas);
        //2.用户关注博主
        List<UserFollow> userFollows = userFollowService.getUserFollows(user.getId());
        modelMap.addAttribute("userFollows", userFollows);

        //3.用户收藏的博客
        modelMap.addAttribute("starBlogs", starBlogService.getUserStarBlogsByUserId(user.getId()));
        return "/blog-home";
    }

    //博客查看页面
    @RequestMapping(value = "/blog/{id}", method = RequestMethod.GET)
    public String viewBlogById(@PathVariable String id, ModelMap modelMap, HttpSession session) {
        //创建容器，用于保存信息
        HashMap<String, Object> hashMap = new HashMap<>();

        //获取博客信息
        Blog blog = blogService.getBlogById(id);
        if (blog == null) {
            return "redirect:/error";
        }


        //获取作者信息
        String authorId = blog.getUserid();
        User author = userService.getUserById(authorId);

        //获取访客信息
        User user = (User) session.getAttribute("user");

        //根据访客和博客状态响应
        if (user != null) {
            if (!authorId.equals(user.getId())) {
                //访客为其他人
                //修改博客访问次数
                blog.setReadcount(blog.getReadcount() + 1);
                if (blog.getBlogstatus() != 1) {
                    return "redirect:/error";
                }
                //增加用户浏览轨迹
                UserTrack userTrack = new UserTrack();
                userTrack.setId(StringUtil.getRandomString(16));
                userTrack.setReadtime(new Date());
                //true为文章，false为问题
                userTrack.setType(true);
                userTrack.setTypeid(id);
                userTrack.setUserid(user.getId());
                userTrack.setTitle(blog.getBlogtitle());
                //保存到数据库中
                userTrackService.saveUserTrack(userTrack);
            }
            //增加用户浏览轨迹
            UserTrack userTrack = new UserTrack();
            userTrack.setId(StringUtil.getRandomString(16));
            userTrack.setReadtime(new Date());
            //true为文章，false为问题
            userTrack.setType(true);
            userTrack.setTypeid(id);
            userTrack.setUserid(user.getId());
            userTrack.setTitle(blog.getBlogtitle());
            //保存到数据库中
            userTrackService.saveUserTrack(userTrack);
        } else {
            //访客为游客
            if (blog.getBlogstatus() != 1) {
                return "redirect:/error";
            }
        }

        //获取作者最新文章信息
        List<Blog> userLatestBlogList = blogService.getUserLatestBlog(authorId);

        //获取作者热门文章
        List<Blog> userHottestBlogList = blogService.getUserHottestBlog(authorId);

        //获取作者个人博客分类
        List<UserBlogType> authorBlogType = blogTypeService.getUserBlogType(authorId);

        //写入数据库
        blogService.updateBlog(blog);

        hashMap.put("blog", blog);
        hashMap.put("author", author);
        hashMap.put("userLatestBlogList", userLatestBlogList);
        hashMap.put("userHottestBlogList", userHottestBlogList);
        hashMap.put("authorBlogType", authorBlogType);

        //添加到request域中
        modelMap.addAttribute(hashMap);
        return "blog-view";
    }

    //用户浏览博客时，添加评论
    @RequestMapping(value = "/addBlogComment", method = RequestMethod.POST)
    @ResponseBody
    public Msg addBlogComment(BlogComment blogComment) {
        //设置id
        blogComment.setId(StringUtil.getRandomString(16));
        //设置edittime
        blogComment.setEdittime(new Date());
        blogCommentService.addBlogComment(blogComment);

        //touserid收到消息提示
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(blogComment.getFromuserid());
        userMessage.setFromusername(blogComment.getFromusername());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("给你发送了一条博客评论 " + blogComment.getComment());
        userMessage.setMessagetype(1);
        userMessage.setMessagetypeid(blogComment.getBlogid());
        userMessage.setUserid(blogComment.getTouserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //按照分页，获取博客评论信息，按照时间逆序排列
    @RequestMapping(value = "/getBlogComments/{blogId}/{pn}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getBlogComments(@PathVariable String blogId, @PathVariable Integer pn) {
        PageHelper.startPage(pn, 10);
        List<BlogComment> comments = blogCommentService.getBlogCommentByBlogId(blogId);
        PageInfo<BlogComment> pageInfo = new PageInfo<>(comments);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //用户支持博客文章操作
    @RequestMapping(value = "/upvoteBlog/{userId}/{blogId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg upvoteBlog(@PathVariable String userId, @PathVariable String blogId) {
        //判断用户是否已支持
        UserUpvoteBlog userUpvoteBlog = new UserUpvoteBlog();
        userUpvoteBlog.setUpvoteblogid(blogId);
        userUpvoteBlog.setUserid(userId);
        if (userUpvoteBlogService.hasUpvoted(userUpvoteBlog)) {
            //已支持，提示用户
            return Msg.fail().add("error", "你已经支持过此文章，请不要重复操作！");
        } else {
            //未支持
            userUpvoteBlog.setId(StringUtil.getRandomString(16));
            userUpvoteBlogService.saveUpvote(userUpvoteBlog);

            //修改博客信息
            Blog blog = new Blog();
            blog.setId(blogId);
            Blog blog_db = blogService.getBlogById(blogId);
            blog.setUpvotenum(blog_db.getUpvotenum() + 1);
            blogService.updateBlog(blog);

            //touserid收到消息提示
            UserMessage userMessage = new UserMessage();
            userMessage.setEdittime(new Date());
            userMessage.setFromuserid(userId);
            userMessage.setFromusername(userService.getUserById(userId).getNickname());
            userMessage.setHasread(0);
            userMessage.setId(StringUtil.getRandomString(16));
            userMessage.setMessagecontent("支持了你发表的文章@ " + blog_db.getBlogtitle() + "。");
            userMessage.setMessagetype(1);
            userMessage.setMessagetypeid(blogId);
            //博客是谁写的
            userMessage.setUserid(blog_db.getUserid());
            userMessageService.saveUserMessage(userMessage);
        }
        return Msg.success();
    }

    //用户反对博客文章操作
    @RequestMapping(value = "/downvoteBlog/{userId}/{blogId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg downvoteBlog(@PathVariable String userId, @PathVariable String blogId) {
        //判断用户是否已反对
        UserDownvoteBlog userDownvoteBlog = new UserDownvoteBlog();
        userDownvoteBlog.setDownvoteblogid(blogId);
        userDownvoteBlog.setUserid(userId);
        if (userDownvoteBlogService.hasDownvoted(userDownvoteBlog)) {
            //已反对，提示用户
            return Msg.fail().add("error", "你已经反对过此文章，请不要重复操作！");
        } else {
            //未反对
            userDownvoteBlog.setId(StringUtil.getRandomString(16));
            userDownvoteBlogService.saveDownvote(userDownvoteBlog);

            //修改博客信息
            Blog blog = new Blog();
            blog.setId(blogId);
            Blog blog_db = blogService.getBlogById(blogId);
            blog.setDownvotenum(blog_db.getDownvotenum() + 1);
            blogService.updateBlog(blog);

            //touserid收到消息提示
            UserMessage userMessage = new UserMessage();
            userMessage.setEdittime(new Date());
            userMessage.setFromuserid(userId);
            userMessage.setFromusername(userService.getUserById(userId).getNickname());
            userMessage.setHasread(0);
            userMessage.setId(StringUtil.getRandomString(16));
            userMessage.setMessagecontent("反对了你发表的文章@ "+blog_db.getBlogtitle()+" 。");
            userMessage.setMessagetype(1);
            userMessage.setMessagetypeid(blogId);
            //博客是谁写的
            userMessage.setUserid(blog_db.getUserid());
            userMessageService.saveUserMessage(userMessage);
        }
        return Msg.success();
    }

    //收藏博客
    @RequestMapping(value = "/starBlog/{userId}/{blogId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg starBlog(@PathVariable String userId, @PathVariable String blogId) {
        //判断用户是否已收藏
        StarBlog starBlog = new StarBlog();
        starBlog.setStarblogid(blogId);
        starBlog.setUserid(userId);
        if (starBlogService.hasStared(starBlog)) {
            //已收藏，提示用户
            return Msg.fail().add("error", "你已经收藏过此文章，请不要重复操作！");
        } else {
            //未收藏
            starBlog.setId(StringUtil.getRandomString(16));
            starBlogService.saveStarBlog(starBlog);
            Blog blog_db = blogService.getBlogById(blogId);

            UserMessage userMessage = new UserMessage();
            userMessage.setEdittime(new Date());
            userMessage.setFromuserid(userId);
            userMessage.setFromusername(userService.getUserById(userId).getNickname());
            userMessage.setHasread(0);
            userMessage.setId(StringUtil.getRandomString(16));
            userMessage.setMessagecontent("收藏了你发表的文章@ "+blog_db.getBlogtitle()+"。");
            userMessage.setMessagetype(1);
            userMessage.setMessagetypeid(blogId);
            //博客是谁写的
            userMessage.setUserid(blog_db.getUserid());
            userMessageService.saveUserMessage(userMessage);
        }
        return Msg.success();
    }

    //举报博客
    @RequestMapping(value = "/report/blog/{blogId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg reportBlog(HttpSession session, @PathVariable String blogId) {
        //判断登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请先登录！");
        }

        Report report = new Report();
        report.setId(StringUtil.getRandomString(16));
        report.setHasread(0);
        report.setReportfieldid(blogId);
        report.setReporttype(1);
        report.setUserid(user.getId());
        //判断是否存在记录
        if (reportService.existReport(report)) {
            return Msg.fail().add("error", "您已举报该博客，请不要重复操作！");
        }
        reportService.saveReport(report);
        Blog blog_db = blogService.getBlogById(blogId);

        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(user.getId());
        userMessage.setFromusername(user.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("举报了你发表的文章@ "+blog_db.getBlogtitle()+"。");
        userMessage.setMessagetype(1);
        userMessage.setMessagetypeid(blogId);
        //博客是谁写的
        userMessage.setUserid(blog_db.getUserid());
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //关注用户
    @RequestMapping(value = "/followUser/{userId}/{followUserId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg followUser(@PathVariable String userId, @PathVariable String followUserId, HttpSession session) {
        UserFollow userFollow = new UserFollow();
        userFollow.setId(StringUtil.getRandomString(16));
        userFollow.setUserid(userId);
        userFollow.setFollowinguserid(followUserId);
        userFollowService.saveUserFollow(userFollow);

        //修改用户数据
        User user1 = new User();
        user1.setId(userId);
        User user1_db=userService.getUserById(userId);
        user1.setFollowingusernum(user1_db.getFollowingusernum() + 1);
        userService.updateUserProfile(user1);
        user1_db.setFollowingusernum(user1.getFollowingusernum());
        //更新session
        session.setAttribute("user", user1_db);

        User user2 = new User();
        user2.setId(followUserId);
        user2.setFannum(userService.getUserById(followUserId).getFannum() + 1);
        userService.updateUserProfile(user2);

        //被关注人收到消息
        UserMessage userMessage = new UserMessage();
        userMessage.setEdittime(new Date());
        userMessage.setFromuserid(userId);
        userMessage.setFromusername(user1_db.getNickname());
        userMessage.setHasread(0);
        userMessage.setId(StringUtil.getRandomString(16));
        userMessage.setMessagecontent("关注了你。");
        userMessage.setMessagetype(2);
        userMessage.setMessagetypeid(userId);
        //谁被关注了
        userMessage.setUserid(followUserId);
        userMessageService.saveUserMessage(userMessage);
        return Msg.success();
    }

    //取消关注
    @RequestMapping(value = "/cancelFollowUser/{userId}/{followUserId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg cancelFollowUser(@PathVariable String userId, @PathVariable String followUserId, HttpSession session) {
        UserFollow userFollow = new UserFollow();
        userFollow.setUserid(userId);
        userFollow.setFollowinguserid(followUserId);
        userFollowService.deleteUserFollow(userFollow);

        //修改用户数据
        User user1 = new User();
        user1.setId(userId);
        user1.setFollowingusernum(userService.getUserById(userId).getFollowingusernum() - 1);
        userService.updateUserProfile(user1);
        //更新session
        session.setAttribute("user", userService.getUserById(userId));

        User user2 = new User();
        user2.setId(followUserId);
        user2.setFannum(userService.getUserById(followUserId).getFannum() - 1);
        return Msg.success();
    }

    //查询是否已关注指定用户
    @RequestMapping(value = "/queryFollowUser/{userId}/{followUserId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg queryFollow(@PathVariable String userId, @PathVariable String followUserId) {
        UserFollow userFollow = new UserFollow();
        userFollow.setUserid(userId);
        userFollow.setFollowinguserid(followUserId);
        if (userFollowService.hasFollowed(userFollow)) {
            //已关注
            return Msg.success().add("flag", "true");
        } else {
            //未关注
            return Msg.success().add("flag", "false");
        }
    }

    //用户勾选领域提交
    @PostMapping("/area-pick")
    public String areaPick(@RequestParam String areas, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        String[] areasArray = areas.split(",");
        if (areasArray.length > 0) {
            UserArea userArea = new UserArea();
            for (String areaId : areasArray) {
                if (areaId.length() != 16) {
                    continue;
                }
                //封装对象，保存到数据库中
                userArea.setId(StringUtil.getRandomString(16));
                userArea.setAbility(0);
                userArea.setAreaid(areaId);
                userArea.setUserid(user.getId());
                userAreaService.saveUserArea(userArea);
            }
            return "redirect:/manageStarArea";
        } else {
            return "area-pick";
        }
    }

    //获取推荐文章
    @GetMapping("/getRecommendBlogs/{pn}")
    @ResponseBody
    public Msg getRecommendBlogs(HttpSession httpSession, @PathVariable Integer pn) {
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请重新登录！");
        }
        PageHelper.startPage(pn, 15);
        List<Blog> blogs = blogService.recommendBlog(user.getId());
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        return Msg.success().add("pageInfo", pageInfo);
    }

    @GetMapping("/manageStarArea")
    public String goToManageStarArea() {
        return "manageStarArea";
    }

    @GetMapping("/manageStarUser")
    public String goToManageStarUser() {
        return "manageStarUser";
    }

    @GetMapping("/manageStarBlog")
    public String goToManageStarBlog() {
        return "manageStarBlog";
    }

    @GetMapping("/blog-area/{areaId}")
    public String goToBlogArea(@PathVariable String areaId, ModelMap modelMap,HttpSession httpSession) {
        //0.判断用户是否登录
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            //用户未登录
            return "redirect:/login";
        }
        //1.用户关注领域
        List<UserArea> userAreas = userAreaService.getUserAreasByUserId(user.getId());
        if (userAreas.isEmpty()) {
            //用户未关注任何领域
            modelMap.addAttribute("areas", areaService.getArea());
            return "area-pick";
        }
        modelMap.addAttribute("userAreas", userAreas);
        //2.用户关注博主
        List<UserFollow> userFollows = userFollowService.getUserFollows(user.getId());
        modelMap.addAttribute("userFollows", userFollows);

        //3.用户收藏的博客
        modelMap.addAttribute("starBlogs", starBlogService.getUserStarBlogsByUserId(user.getId()));
        modelMap.addAttribute("area", areaService.getArea(areaId));

        return "/blog-area";
    }

    //获取指定领域下的所有博客
    @GetMapping(value = "/getAllBlogsByAreaId/{areaId}/{pn}")
    @ResponseBody
    public Msg getAllBlogsByAreaId(@PathVariable String areaId, @PathVariable Integer pn) {
        PageHelper.startPage(pn, 15);
        List<Blog> blogs = blogService.getAllBlogsByAreaId(areaId);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        return Msg.success().add("pageInfo", pageInfo);
    }
}